//
//  LoginVM.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/6/21.
//

import RxSwift
import Combine
import ToastUI
import Moya

class LoginViewModel: ObservableObject {
    
    @Published var username = ""
    @Published var password = ""
    @Published var code = ""
    @Published var passwordAgain = ""

    @Published var newPassword = ""
    @Published var oldPassword = ""
    @Published var phoneNumber = ""
    
//    @Published var mobile = ""
//    @Published var scene = ""
    @Published var isSendSuccess = false

    // 状态管理
    @Published var isLoading = false
    @Published var error: String?
    @Published var isLoginSuccess = false
    @Published var isupdateSuccess = false
    @Published var isLogoutSuccess = false

    @Published var selectedCode = "+86"
    @Published var isCodePickerPresented = false
    
    @Published var needBindMobile = false
    @Published var isbindSuccess = false

    @Published var captchaImage: UIImage?
    var captchaImageUUID = ""
    
    var countryCodes = ["中国大陆 ‌：+86","香港 ‌：+852","澳门 ‌：+853","台湾 ‌：+886","美国 ‌：+1‌","加拿大 ‌：+1","澳大利亚 ‌：+61","英国 ‌：+44","法国 ‌：+33","德国 ‌：+49","日本 ‌：+81","韩国 ‌：+82","阿根廷 +54","巴西 +55"]
    
    private let disposeBag = DisposeBag()
    
    init() {
        refreshCaptchaImage()
    }
    
    func login() {
        isLoading = true
        error = nil
        
//        NetworkManager.shared.login(
//            username: username,
//            password: password,
//            code: code,
//            uuid: captchaImageUUID
//        )
//        .observe(on: MainScheduler.instance)
//        .subscribe(
//            onSuccess: { [weak self] response in
//                guard response.code == 200 else {
//                    self?.error = response.msg
//                    return
//                }
//                self?.isLoading = false
//                self?.isLoginSuccess = true
//                print(response);
//                self?.error = nil
//                self?.captchaImage = nil
//                self?.captchaImageUUID = ""
//                guard let token = response.token else {
//                    return
//                }
//                TokenManager.shared.accessToken = "Bearer " + token
//            },
//            onFailure: { [weak self] error in
//                self?.isLoading = false
//                self?.error = error.localizedDescription
//                print(error);
//            }
//        )
//        .disposed(by: disposeBag)
        
        NetworkManager.shared.request(MultiTarget(ApiService.login(username: username, password: password, code: code, uuid: captchaImageUUID)), responseType: LoginResponse.self)
        .observe(on: MainScheduler.instance)
        .subscribe(
            onNext: { [weak self] response in
                self?.isLoading = false
                self?.isLoginSuccess = true
                print(response);
                self?.error = nil
                self?.captchaImage = nil
                self?.captchaImageUUID = ""
                guard let token = response.token else {
                    return
                }
                TokenManager.shared.accessToken = "Bearer " + token
            },
            onError: { [weak self] error in
                self?.handleError(error)
                print(error);
            }
        )
        .disposed(by: disposeBag)
    }
    
    
    func sendSMCcode(mobile:String , scene: String) {
        isLoading = true
        error = nil
//        NetworkManager.shared.sendSMCcode(mobile:mobile , scene: scene)
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    guard response.code == 200 else {
//                        self?.error = response.msg
//                        return
//                    }
//                    self?.isLoading = false
//                    self?.isSendSuccess = true
//                    print(response);
//                    self?.error = nil
//                },
//                onFailure: { [weak self] error in
//                    self?.isLoading = false
//                    self?.error = error.localizedDescription
//                    print(error);
//                }
//            )
//            .disposed(by: disposeBag)
        
        NetworkManager.shared.request(MultiTarget(ApiService.sendSMCcode(mobile: mobile, scene: scene)), responseType: SimpleResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.isLoading = false
                    self?.isSendSuccess = true
                    print(response);
                    self?.error = nil
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    func loginByCode(mobile:String , code: String){
        isLoading = true
        error = nil
//        NetworkManager.shared.loginByCode(mobile: mobile, code: code)
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    guard response.code == 200 else {
//                        self?.error = response.msg
//                        return
//                    }
//                    self?.isLoading = false
//                    self?.isLoginSuccess = true
//                    print(response);
//                    TokenManager.shared.accessToken = response.data.token
//                    UserConfigManager.shared.userId = String(response.data.user.id)
//                    self?.error = nil
//                },
//                onFailure: { [weak self] error in
//                    self?.isLoading = false
//                    self?.error = error.localizedDescription
//                    print(error);
//                }
//            )
//            .disposed(by: disposeBag)
        NetworkManager.shared.request(MultiTarget(ApiService.loginByCode(mobile: mobile, code: code)), responseType: PhoneLoginResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.isLoading = false
                    self?.isLoginSuccess = true
                    print(response);
                    TokenManager.shared.accessToken = response.data.token
                    UserConfigManager.shared.userId = String(response.data.user.id)
                    self?.error = nil
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    func logOut() {
//        NetworkManager.shared.logout()
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    guard response.code == 200 else {
//                        self?.error = response.msg
//                        return
//                    }
//                    self?.isLoading = false
//                    self?.isLogoutSuccess = true
//                    print(response);
//                    self?.error = nil
//                },
//                onFailure: { [weak self] error in
//                    self?.isLoading = false
//                    self?.error = error.localizedDescription
//                    print(error);
//                }
//            )
//            .disposed(by: disposeBag)
        NetworkManager.shared.request(MultiTarget(ApiService.logout), responseType: SimpleResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    
                    self?.isLoading = false
                    self?.isLogoutSuccess = true
                    print(response);
                    self?.error = nil
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    
    
    func refreshCaptchaImage() {
//        NetworkManager.shared.refreshCaptchaImage()
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    guard response.code == 200 else {
//                        self?.error = response.msg
//                        return
//                    }
//                    guard let base64String = response.img, !base64String.isEmpty else {
//                        self?.error = "验证码图片获取失败"
//                        return
//                    }
//
//                    if let image = self?.base64ToImage(base64String: base64String) {
//                        self?.captchaImage = image
//                    }
//                    guard let uuid = response.uuid, !uuid.isEmpty else {
//                        return
//                    }
//                    self?.captchaImageUUID = uuid
//                }, onFailure: { error in
//                    print("获取验证码失败")
//                }
//            )
//            .disposed(by: disposeBag)
        
        NetworkManager.shared.request(MultiTarget(ApiService.captchaImage), responseType: CaptchaImage.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    
                    guard let base64String = response.img, !base64String.isEmpty else {
                        self?.error = "验证码图片获取失败"
                        return
                    }
                    
                    if let image = self?.base64ToImage(base64String: base64String) {
                        self?.captchaImage = image
                    }
                    guard let uuid = response.uuid, !uuid.isEmpty else {
                        return
                    }
                    self?.captchaImageUUID = uuid
                },
                onError: {[weak self] error in
                    self?.handleError(error)
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    func updatePassword () {
        isLoading = true
        error = nil
//        NetworkManager.shared.updatePassWord(newPassword: newPassword, oldPassword: oldPassword)
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    guard response.code == 200 else {
//                        self?.error = response.msg
//                        return
//                    }
//                    self?.isLoading = false
//                    self?.isupdateSuccess = true
//                    print(response);
//                },
//                onFailure: { [weak self] error in
//                    self?.isLoading = false
//                    self?.handleError(error)
//                    print(error);
//                }
//            )
//            .disposed(by: disposeBag)
        
        NetworkManager.shared.request(MultiTarget(ApiService.updatePwd(newPassword: newPassword, oldPassword: oldPassword)), responseType: SimpleResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.isLoading = false
                    self?.isupdateSuccess = true
                    print(response);
                },
                onError: { [weak self] error in
                    self?.isLoading = false
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }

    
    
    
    
    
    private func handleError(_ error: Error) {
        self.isLoading = false
        if let networkError = error as? NetworkError {
            self.error = networkError.errorDescription
//            if networkError.isAuthenticationError {
//                AppState.shared.logout()
//            }
        } else {
            self.error = error.localizedDescription
        }
    }
    
    func base64ToImage(base64String: String) -> UIImage? {
        guard let data = Data(base64Encoded: base64String) else {
            return nil
        }
        return UIImage(data: data)
    }
    
    //三方授权登录
    func oauthLogin(oauthType:String, openid:String, accessToken:String, unionid: String){
        NetworkManager.shared.request(MultiTarget(ApiService.oauthLogin(oauthType: oauthType, openid: openid, accessToken: accessToken, unionid: unionid)), responseType: WeChatResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    print(response);
                    self?.needBindMobile = response.data.needBindMobile
                    self?.error = nil
                    if response.data.needBindMobile == false {
                        TokenManager.shared.accessToken = response.data.token
                        UserConfigManager.shared.userId = String(response.data.user.id)
                    }
                    self?.isbindSuccess = true
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                    self?.isbindSuccess = false
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    //绑定手机号
    func bindMobile(accessToken:String,oauthType:String,openid:String,unionid:String,mobile:String,code:String) {
        NetworkManager.shared.request(MultiTarget(ApiService.bindMobile(accessToken: accessToken,oauthType: oauthType, openid: openid, unionid: unionid, mobile: mobile, code: code)), responseType: PhoneLoginResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.isLoading = false
                    print(response);
                    TokenManager.shared.accessToken = response.data.token
                    UserConfigManager.shared.userId = String(response.data.user.id)
                    self?.error = nil
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }
    
    
    
    
}
